package com.feiwo.nonego.rpc.reflect.asm;

import com.feiwo.nonego.rpc.reflect.api.ReflectInvoker;
import com.feiwo.nonego.rpc.reflect.asm.proxy.ReflectProxy;
import com.feiwo.nonego.rpc.spi.annotation.SPIClass;

import java.lang.reflect.InvocationHandler;

/**
 *
 *
 * @author feiwo 2025-08-17
 */
@SPIClass
public class AsmReflectInvoker implements ReflectInvoker {
    @Override
    public Object invoke(Object serviceBean, Class<?> serviceClass, String methodName, Class<?>[] parameterTypes, Object[] parameters) throws Throwable {
        var constructor = serviceClass.getConstructor(new Class[]{});
        var constructorParam = new Object[]{};
        var instance = ReflectProxy.newProxyInstance(AsmReflectInvoker.class.getClassLoader(), getInvocationHandler(serviceBean), serviceClass, constructor, constructorParam);
        var method = serviceClass.getMethod(methodName, parameterTypes);
        method.setAccessible(true);
        return method.invoke(instance, parameters);
    }

    private InvocationHandler getInvocationHandler(Object obj) {
        return (proxy, method, args) -> {
          method.setAccessible(true);
          return method.invoke(obj,args);
        };
    }
}
